//
//  NSDictionary+KLException.m
//  KoalaUtilKit
//
//  Created by Tommy on 15/1/29.
//  Copyright (c) 2015年 Koala Team. All rights reserved.
//

#import "NSDictionary+KLException.h"
#import "NSObject+KLSwizzle.h"
#import "KLLog.h"

@implementation NSDictionary (KLException)

#if KLENABLE_EXCEPTION_SWIZZLE

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self kl_swizzleClassSelector:@selector(dictionaryWithObjects:forKeys:count:) withNewSelector:KLHookedSel(dictionaryWithObjects:forKeys:count:)];
    });
}

+ (void) _kl_removePairObjects:(const id [])objects keys:(const id <NSCopying> [])keys at:(NSUInteger) index count:(NSUInteger)cnt{
    __unsafe_unretained id* objs = (__unsafe_unretained id*) objects;
    __unsafe_unretained id* tmpKeys = (__unsafe_unretained id*) keys;
    for(NSUInteger i=index;i<cnt&&(i+1)<cnt;++i){
        objs[i] = objs[i+1];
    }
    
    for(NSUInteger i=index;i<cnt&&(i+1)<cnt;++i){
        tmpKeys[i] = tmpKeys[i+1];
    }

}
+ (instancetype)KLHookedMethod(dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt){
    NSUInteger count = cnt;
    for(NSUInteger i = 0; i < count; ++i){
        if(!objects[i] || !keys[i]) {
            NSAssert(0,@"insert nil at %d to dictionary",i);
            KLLogError(@"insert nil at %d to dictionary",i);
            [self _kl_removePairObjects:objects keys:keys at:i count:count--];
        }
    }
    
    return [self KLHookedMethod(dictionaryWithObjects:objects forKeys:keys count:count)];
}

#endif //KLENABLE_EXCEPTION_SWIZZLE

@end
